# -*- coding: utf-8 -*-
import re,urllib
from settings import *
from django.shortcuts import render_to_response
from django.template import context
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, InvalidPage

def tiny_url(url):
    u"""
    summary:
        将url转换成tinyurl
    author:
        Jason Lee <huacnlee@gmail.com>
    """
    apiurl = "http://tinyurl.com/api-create.php?url="
    tinyurl = urllib.urlopen(apiurl + url).read()
    return tinyurl

def content_tiny_url(content):
    u"""
    summary:
        让消息里面的连接转换成更短的Tinyurl
    author:
        Jason Lee <huacnlee@gmail.com>
    """

    regex_url = r'http:\/\/([\w.]+\/?)\S*'
    for match in re.finditer(regex_url, content):
        url = match.group(0)
        content = content.replace(url,tiny_url(url))

    return content

def format_comment(context,encode=True):
    u"""
    summary:
        格式化评论，清除HTML标签，并把空格换成 &nbsp; 再把换行换成 <br />
    params:
        content [str]    内容
        encode  [bool]    True加密[default],False解密
    """
    text_array = ('<','>',' ','\r\n','\n','\r')
    html_array = ('&lt;','&gt;','&nbsp;','<br />','<br />','<br />')
    if encode:
        i = 0
        for t in text_array:            
            context = context.replace(t,html_array[i])
            i = i + 1
    else:
        i = 0
        for h in html_array:            
            context = context.replace(t,text_array[i])
            i = i + 1
    return context

def substr(content, length,add_dot=True):
    u"""
    summary:
        字符串截取
    author:
        Jason Lee <huacnlee@gmail.com>
    """
    if(len(content) > length):
        content = content[:length]
        if(add_dot):
            content = content[:len(content)-3] + '...'
    return content


   
def pagebar(paginator,page_index,page_size,owner=None,url_format=None):
    u"""
    summary:
        生成HTML分页控件,要使用tempate
    params:
        paginator     Paginator实体 Paginator(objects, page_size)
        page_index  当前页数
        owner        博客主信息，没有传空
        url_format    如：/user/huacn/%s/    分页的数字用%s只能有一个存在
    author:
        Jason Lee <huacnlee@gmail.com>
    """
    if not url_format:
        url_format = '/list/%s/'
    page_index = int(page_index)

    return render_to_response('components/pagebar.html', {
        'owner' : owner,
        'paginator' : paginator,
        'has_pages': paginator.num_pages > 1,
        'has_next': paginator.page(page_index).has_next(),
        'has_prev': paginator.page(page_index).has_previous(),
        'page_index': page_index,
        'page_next': page_index + 1,
        'page_prev': page_index - 1,
        'page_count': paginator.num_pages,
        'row_count' : paginator.count,
        'page_nums': range(paginator.num_pages+1)[1:],
        'page_url' : url_format,
    }).content
